import os


class ConfigItem:
    section = 'default'
    name = None
    value = None

    def __init__(self, section=None, name=None, value=None):
        if section is not None: self.section = section
        self.name = name
        self.value = value

    def set_section(self, section):
        self.section = section

    def set_name(self, name):
        self.name = name

    def set_value(self, value):
        self.value = value

    def from_string(self, _str):
        val = _str.split('=', 2)

        if len(val) == 2:
            self.name = val[0]
            self.value = val[1]
        elif len(val) == 3:
            self.section = val[0]
            self.name = val[1]
            self.value = val[2]

    def to_string(self):
        _str = '='.join([self.section, self.name, self.value])
        return _str


class Config:
    items = []
    section = ''

    def __init__(self, filename):
        self.config_file = filename

    def set_file(self, filename):
        self.config_file = filename

    def load(self, filename=None):
        if filename is not None: self.config_file = filename
        if not os.path.exists(self.config_file): self.save()
        f = open(self.config_file, 'r')
        for line in f:
            line = line.strip(' \n\r')
            if len(line) < 1: continue
            elif line.startswith('['):
                self.section = line.replace('[', '').replace(']', '')
                continue
            else:
                itm = ConfigItem()
                itm.from_string(self.section + '=' + line)
                self.items.append(itm)
        f.close()
        self.section = ''

    def save(self, filename=None):
        if filename is not None: self.config_file = filename
        f = open(self.config_file, 'w')
        self.section = ''
        for itm in self.items:
            if itm.section != self.section:
                f.write('[' + itm.section + ']\n')
                self.section = itm.section
            f.write(itm.name + '=' + itm.value + '\n')
        f.close()
        self.section = ''

    def get(self, section, name):
        for itm in self.items:
            if itm.section == section and itm.name == name:
                return itm.value
        return None

    def set(self, section, name, value):
        for i in range(len(self.items)):
            itm = self.items[i]
            if itm.section == section and itm.name == name:
                self.items[i].value = value
                return True
        self.items.append(ConfigItem(section, name, value))
